package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.additional.update.impl.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmMaterialService;
import org.apache.kafka.common.protocol.types.Field;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FastDFSClient fastDFSClient;

    @Value("${fdfs.url}")
    private String fileURL;

    @Resource
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult fileUpload(MultipartFile multipartFile) {
        //检查参数是否为空
        if(multipartFile==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //上传fastdfs
        String fileId=null;
        try {
            fileId = fastDFSClient.uploadFile(multipartFile);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"上传失败");
        }
        //保存到数据库
        WmMaterial wm = new WmMaterial();
        //设置时间
        wm.setCreatedTime(new Date());
        //是否收藏
        wm.setIsCollection(0);
        //图片的类型 1视频 0图片
        wm.setType(0);
        WmUser user = WmThreadLocalUtils.getUser();
        System.out.println(user.getApUserId());
        wm.setUserId(user.getApUserId());
        wm.setUrl(fileURL+fileId);
        save(wm);
        return ResponseResult.okResult(wm);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //检查参数
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //设置条件
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        //获取userId
        Integer userId = WmThreadLocalUtils.getUser().getApUserId();
        queryWrapper.eq(WmMaterial::getUserId,userId);
        queryWrapper.eq(dto.getIsCollection()!=null, WmMaterial::getIsCollection,dto.getIsCollection());
        Page pageInfo = new Page<>(dto.getPage(), dto.getSize());
        IPage page = page(pageInfo, queryWrapper);
        //封装数据
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    @Override
    public ResponseResult delById(Integer id) {
        //判断参数
        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断素材跟新闻是否关联
        //根据id去素材关联表中查询数据
        LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WmNewsMaterial::getMaterialId,id);
        //查询记录数
        Integer count = wmNewsMaterialMapper.selectCount(lambdaQueryWrapper);
        if(count>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"素材跟新闻关联，不能删除");
        }
        //删除fastdfs的内容
        //查询素材表中的记录
        WmMaterial wmMaterial=getById(id);
        //去除
        String url = wmMaterial.getUrl().replace(fileURL, "");
        fastDFSClient.delFile(url);
        //删除素材表中的记录
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult setIsCollection(Integer id, Integer type) {
        //判断参数
        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //设置局部修改的字段
        LambdaUpdateWrapper<WmMaterial> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(WmMaterial::getIsCollection,type);
        lambdaUpdateWrapper.eq(WmMaterial::getId, id);
        //修改
        update(lambdaUpdateWrapper);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
